//
//  CZDetailStstusController.swift
//  GZWeibo666
//
//  Created by mac on 15/12/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import SDWebImage

import SVPullToRefresh

import SVProgressHUD

class CZDetailStstusController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    var status:CZStatus?

    var comments:[CZComments]?
        {
        didSet
        {
            comments?.first?.updateState = false
            self.tableview.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadData()
        self.prepareTableView()
        
    }
    
    //刚进入页面加载的评论数据
    func loadData()
    {
        let since_id = self.comments?.first?.id ?? 0
     
        
        CZComments.loadComments(since_id,max_id: 0,id: (status?.id)!, finished: { (result, error) -> () in
            print("status?.id = \(self.status?.id)")
            //更改属性
//            self.comments?.first?.updateState = false
            if error != nil && result == nil
            {
                SVProgressHUD.showErrorWithStatus("网络不给力")
                return
            }
        let count = result?.count ?? 0
            
            
            if count == 0
            {
                if since_id > 0
                {
                    self.comments?.first?.updateState = false
                SVProgressHUD.showSuccessWithStatus("没有新的评论了")
                    self.tableview.reloadData()
                }
                return
            }
            
            if since_id > 0
            {
                SVProgressHUD.showSuccessWithStatus("加载\(count)条数据")
                self.comments?.first?.updateState = false
                self.comments = result! + self.comments!
                self.tableview.reloadData()
                
            }
            else
            {
                self.comments = result
            }
            
            
           
        })
    }
    
    private func prepareTableView() {
        
        
        navigationItem.title = "微博正文"
        //隐藏cell分割线
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        //添加子控件
        self.view.addSubview(tableview)
        self.view.addSubview(bottom)


        tableview.estimatedRowHeight = 60
        
        // 注册cell,需要注册4个,根据显示的模型返回对应类型的cell
        tableview.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.NormalCell.rawValue)
        tableview.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.ForwardCell.rawValue)
        //数据显示cell
        tableview.registerClass(CZDetailStstusCell.self, forCellReuseIdentifier: "cell")
        //更新数据的cell
        tableview.registerClass(CZDetailStstusUpdateCell.self, forCellReuseIdentifier: "updatecell")

        tableview.dataSource = self
        tableview.delegate = self
        
//        print(view)
        
        
        bottom.frame = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 44, width: UIScreen.mainScreen().bounds.width, height: 44)
        
        //        bottom.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: self.view, size:  CGSize(width: UIScreen.mainScreen().bounds.width, height: 44), offset: CGPoint(x: 0, y: -88))
       
        bottom.forwardButton.addTarget(self, action: "forwardButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        bottom.commentButton.addTarget(self, action: "commentButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        bottom.likeButton.addTarget(self, action: "likeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        print("\(bottom.frame.origin.x)\(bottom.frame.origin.y)")
        
        tableview.addInfiniteScrollingWithActionHandler { () -> Void in
            print("加载更多数据")
            self.loadMoreStatus()
        }
        
    }
    
    //上拉加载数据
    func loadMoreStatus() {
        
        let max_id = comments?.last?.id ?? 0
        
        CZComments.loadComments(0,max_id: max_id,id: (status?.id)!, finished: { (result, error) -> () in
            print("status?.id = \(self.status?.id)")
           self.tableview.infiniteScrollingView.stopAnimating()
            
            if error != nil && result == nil
            {
                SVProgressHUD.showErrorWithStatus("网络不给力")
                return
            }
            let count = result?.count ?? 0
            
            if count == 0
            {
                if max_id > 0
                {
                SVProgressHUD.showSuccessWithStatus("已经到底了")
                }
                return
            }
            else
            {
                SVProgressHUD.showSuccessWithStatus("加载\(count)条评论")
                self.comments = self.comments! + result!
            }
            
        })
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("comments = \(self.comments?.count)")
        
        if section == 0
        {
            return 1
        }
        else
        {
        return  self.comments?.count ?? 1
        }
    }
    
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if indexPath.section == 0
        {
            return headView
        }

        let count = self.comments?.count ?? 0
        
        if count == 0
        {
            return NoneCommentCell
        }
        let comment = self.comments![indexPath.row]
        
        if comment.updateState
        {
            let cell = tableview.dequeueReusableCellWithIdentifier("updatecell") as! CZDetailStstusUpdateCell
            return cell
            
        }
         let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! CZDetailStstusCell

        cell.comment = comment

        return cell
    }
    
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if(indexPath.section == 0)
        {
            if status!.rowHeight != nil {
                return status!.rowHeight!
            }

            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            // cell计算行高
            let rowHeight = cell.rowHeight(status!)
            
            // 缓存行高
            status!.rowHeight = rowHeight

            return rowHeight
  
        }
        else
        {

            let count = self.comments?.count ?? 0
            
            if count == 0
            {
                return 44
            }
            
            
            let comment = self.comments![indexPath.row]
            
            if comment.updateState
            {
                return 44
            }
            
            if comment.rowHeight != nil
            {
                print("缓存行高 = \(comment.rowHeight!)")
                return comment.rowHeight!
            }
            
            let cell = tableview.dequeueReusableCellWithIdentifier("cell") as! CZDetailStstusCell
            let height = cell.rowHeight(comment)
            comment.rowHeight = height
            print("计算行高 = \(height)")
            return height
        }
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1
        {
            return 44
        }
        else
        {
            return 0
        }
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1
        {
            return hh
        }
        else
        {
        return nil
        }
    }
    
    //转发
    func forwardButtonClick()
    {
        print("转发")
        let vc = CZInteractionViewController()
        vc.status = status
        vc.account = CZUserAccount.loadUserAccount()?.screen_name ?? "iOS06"
        vc.type = InteractionType.forward
        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
        
    }
    
    //评论
    func commentButtonClick()
    {
        let vc = CZInteractionViewController()
        vc.status = status
        vc.account = CZUserAccount.loadUserAccount()?.screen_name ?? "iOS06"
        vc.type = InteractionType.comment
        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    //点赞
    func likeButtonClick()
    {
        SVProgressHUD.showErrorWithStatus("词功能暂未开放,敬请期待!!!")
    }
    
    ///懒加载评论cell
    lazy var NoneCommentCell:UITableViewCell = {
    
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
        let lable = UILabel()
        lable.text = "暂时没有评论"
        lable.textColor = UIColor.lightGrayColor()
        lable.sizeToFit()
        cell.contentView.addSubview(lable)
        lable.center = cell.contentView.center
        cell.textLabel?.font = UIFont.systemFontOfSize(12)
        
        return cell
    }()
    
    
    ///懒加载tableview
    lazy var tableview: UITableView = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height - 44), style: UITableViewStyle.Plain)
    
    ///懒加载表头
    private lazy var headView:CZStatusCell = {
        
        var head:CZStatusCell
        if self.status!.retweeted_status == nil
        {
            head = CZStatusNormalCell()
        }
        else
        {
            head = CZStatusForwardCell()
        }
        
        head.status = self.status
        head.delegate = self
        return head
    }()
    
    ///懒加载bottom
    private lazy var bottom:CZStatusBottomView = CZStatusBottomView()
    
    //第二组组头
    private lazy var hh:UIView = {
    
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.9, alpha: 0.9)
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
        let commentCount = "评论:" + (self.headView.bottomView.commentButton.titleLabel?.text)!
        let button = UIButton(imageName: "", title: commentCount)
        button.frame = CGRect(x: 0, y: 5, width: 50, height: 30)
//        button.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 50, height: 30))
//        button.center = view.center
//        
//        button.setTitle(commentCount, forState: UIControlState.Normal)
//        button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
        button.sizeToFit()
        button.addTarget(self, action: "updata", forControlEvents: UIControlEvents.TouchUpInside)
        
        view.addSubview(button)
        return view
    }()
    
    //刷新数据
    func updata()
    {
//        print("shuaxin")
        self.comments?.first?.updateState = true
        tableview.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Bottom)
        
        self.loadData()
    }

    
}



class CZDetailStstusCell:UITableViewCell
{
    var comment:CZComments?
        {
        didSet
        {
            iconView.sd_setImageWithURL(NSURL(string: (comment?.user?.profile_image_url)!))
            nameLable.text = comment?.user?.screen_name
            timeLable.text = comment?.created_at
            textLable.text = comment?.text
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.prepareUI()
    }

    //添加控件
    func prepareUI()
    {
        self.contentView.addSubview(iconView)
        self.contentView.addSubview(nameLable)
        self.contentView.addSubview(timeLable)
        self.contentView.addSubview(textLable)
        
        //取消自动布局
        iconView.translatesAutoresizingMaskIntoConstraints = false
        nameLable.translatesAutoresizingMaskIntoConstraints = false
        timeLable.translatesAutoresizingMaskIntoConstraints = false
        textLable.translatesAutoresizingMaskIntoConstraints = false
        
        //添加约束
        
        iconView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: 8, y: 8))
        
        
//        nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: CZStatusCellMargin, y: 0))
        nameLable.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 3, y: 0))
//        timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: CZStatusCellMargin, y: 0))
        timeLable.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 3, y: 0))
        
        textLable.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: timeLable, size: nil, offset: CGPoint(x: 0, y: 3))
        
        contentView.addConstraint(NSLayoutConstraint(item: textLable, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.mainScreen().bounds.width - 50 - 6 - 8))
        
    }
    
    
    //计算行高
    func rowHeight(comment:CZComments) -> CGFloat
    {
       self.comment = comment
        
        self.layoutIfNeeded()
        return CGRectGetMaxY(textLable.frame)
    }
    
    //图标
    private lazy var iconView:UIImageView = {
    
        let image = UIImageView()
        
        return image
    }()
   
    ///名字
    private lazy var nameLable:UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    //时间
    private lazy var timeLable:UILabel = UILabel(color: UIColor.orangeColor(), fontSize: 9)
    //内容
    private lazy var textLable:UILabel = {
        let label = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
        
        // 设置换行
        label.numberOfLines = 0
        
        return label
    }()
}


//更新数据时第一行显示的cell
class CZDetailStstusUpdateCell:UITableViewCell
{
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.prepareUI()
    }
    
    func prepareUI()
    {
        contentView.addSubview(loadImage)
        loadImage.ff_AlignInner(type: ff_AlignType.TopCenter, referView: contentView, size: nil)
        self.setAnimation()
        
    }
    
    func setAnimation()
    {
        // 旋转的核心动画
        let rotation = CABasicAnimation(keyPath: "transform.rotation")
        
        // 设置动画参数
        rotation.toValue = 2 * M_PI
        rotation.duration = 0.25
        rotation.repeatCount = MAXFLOAT
        
        // 添加到图层,开始动画
        loadImage.layer.addAnimation(rotation, forKey: nil)
    }
    
    private lazy var loadImage:UIImageView = {
  
        let image = UIImageView(image: UIImage(named: "tableview_loading"))
 
        return image
    }()
    
    
    
}


extension CZDetailStstusController:CZStatusCellDelegate
{
    func detailstatus(status:CZStatus)
    {
    }
    
    func forwardButtonDidClick(status:CZStatus)
    {
        self.forwardButtonClick()
        
//        let vc = CZInteractionViewController()
//        vc.status = status
//        vc.account = CZUserAccount.loadUserAccount()?.screen_name ?? "iOS06"
//        vc.type = InteractionType.forward
//        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    func commentButtonDidClick(status:CZStatus)
    {
        self.commentButtonClick()
        
//        let vc = CZInteractionViewController()
//        vc.status = status
//        vc.account = CZUserAccount.loadUserAccount()?.screen_name ?? "iOS06"
//        vc.type = InteractionType.comment
//        presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    func likeButtonDidClick(status:CZStatus)
    {
        self.likeButtonClick()
//        SVProgressHUD.showErrorWithStatus("词功能暂未开放,敬请期待!!!")
    }
}






